package top.lucas9.wechat.push.service.impl;

/**
 * @author lucas9
 * @date 2022/11/26 11:46
 */

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Service;
import top.lucas9.wechat.push.config.WechatAppProperties;
import top.lucas9.wechat.push.entity.User;
import top.lucas9.wechat.push.service.PushService;

/**
 * @author lucas9
 * @date 2022/11/26 11:30
 */
@Slf4j
@Service
public class PushServiceImpl implements PushService {
    private final WechatAppProperties wechatAppProperties;

    public PushServiceImpl(WechatAppProperties wechatAppProperties) {
        this.wechatAppProperties = wechatAppProperties;
    }

    public boolean push(User user, String templateId) {
        //1，配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(wechatAppProperties.getId());
        wxStorage.setSecret(wechatAppProperties.getSecret());
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        // 推送消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(user.getOpenId())
                .templateId(templateId)
                .build();
//        templateMessage.addData(new WxMpTemplateData("NORMAL","1"));
//        long birthdays = DateUtil.daysToBirthday(user.getBirthday());
//        templateMessage.addData(new WxMpTemplateData("date", "2022-11-26 晴", "#00BFFF"));
//        templateMessage.addData(new WxMpTemplateData("weather", "xx", "#00FFFF"));
//        templateMessage.addData(new WxMpTemplateData("low", "xx", "#173177"));
//        templateMessage.addData(new WxMpTemplateData("temp", "xx", "#EE212D"));
//        templateMessage.addData(new WxMpTemplateData("high", "xx", "#FF6347"));
//        templateMessage.addData(new WxMpTemplateData("city", "xx", "#173177"));
//        templateMessage.addData(new WxMpTemplateData("loveDays", "10" + "", "#FF1493"));
//        templateMessage.addData(new WxMpTemplateData("birthdays", birthdays + "", "#FFA500"));
//        templateMessage.addData(new WxMpTemplateData("remark", "remark", "#FF1493"));
        templateMessage.addData(new WxMpTemplateData("data", "测试内容"));
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            return true;
        } catch (Exception e) {
            log.error("消息推送失败", e);
            return false;
        }
    }
}
